package com.mmall.concurrency.example.sync;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public class SynchronizedExample2 {

    // 修饰一个类
    public static void test1() {
        synchronized (SynchronizedExample2.class) {
            log.info("线程：" + Thread.currentThread().getId() + "在访问同步代码块");
            log.info("线程：" + Thread.currentThread().getId() + "现在休眠2秒");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("线程：" + Thread.currentThread().getId() + "现在结束访问");
        }
    }

    public void test2() {
        log.info("线程：" + Thread.currentThread().getId() + "在访问非同步代码块");
        log.info("线程：" + Thread.currentThread().getId() + "结束访问非同步代码块");
    }

    public static void main(String[] args) {
        SynchronizedExample2 example1 = new SynchronizedExample2();
        SynchronizedExample2 example2 = new SynchronizedExample2();
        SynchronizedExample2 example3 = new SynchronizedExample2();
        SynchronizedExample2 example4 = new SynchronizedExample2();
        ExecutorService executorService = Executors.newCachedThreadPool();
        /**
         * 此处开了2个线程访问同一个对象的两个不同的个方法，由于是类修饰的，阻塞类的所有对象
         * 没有添加synchronized的代码不会被阻塞
         */
        executorService.execute(() -> {
            example1.test1();
            example2.test1();
        });
//        executorService.execute(() -> {
//            example2.test1();
//        });
        executorService.execute(() -> {
            example3.test1();
        });
//        executorService.execute(() -> {
//            example4.test2();
//        });
        executorService.shutdown();
    }
}
